package com.xctech.yace.util;

import org.apache.flink.api.java.utils.ParameterTool;

import java.util.HashMap;
import java.util.Map;

public class AuthSaslPlainUtil {

    private static final String startRegex = "ENC(";
    private static final String endRegex = ")";
    public static final String jasyptPwConf = "jasypt.password";
    /**
     * 这里检查所有的ENC(xxx),转换密文
     * @param tool
     * @return
     */
    public static Map<String, String> replaceEnPassword(ParameterTool tool){
        Map<String, String> map = new HashMap<>();
        Map<String, String> confs = tool.toMap();
        String jasyptPw = tool.get(jasyptPwConf,"etl");
        for (Map.Entry<String, String> e : confs.entrySet()) {
            String key = e.getKey();
            String value = e.getValue();
            if(value.startsWith(startRegex) && value.endsWith(endRegex)){
                try{
                    map.put(key,JasyptUtils.decryptText(jasyptPw, value));
                }catch (Exception e1){
                    throw new RuntimeException("请检查密码参数:"+key+",密文ENC(xxx)解密失败,请核对jasypt.password入参是否正确,校验加密是否正确!!!");
                }
            }
        }
        return map;
    }

    /**
     * 单个特定转成value,ENC(xxx),转换密文
     * @param jasyptPw
     * @param password
     * @return
     */
    public static String replaceEnPassword(String jasyptPw,String password){
        String res = password;
        if(password.startsWith(startRegex) && password.endsWith(endRegex)){
            try{
                res = JasyptUtils.decryptText(jasyptPw, password);
            }catch (Exception e1){
                throw new RuntimeException("请检查密码参数:"+password+",密文ENC(xxx)解密失败,请核对jasypt.password入参是否正确,校验加密是否正确!!!");
            }
        }
        return res;
    }
}
